package com.haotunet.app.goldtreasure.activity;

import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.StoreInfo;
import com.haotunet.app.goldtreasure.model.StoreModel;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.LocationUtils;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.views.TitleView;

import java.util.List;

public class NearGoldShopActivity extends BaseActivity implements OnMapClickListener {
	private TitleView mTitleView;
	private MapView mMapView;
	private BaiduMap mBaiduMap;
	private LatLng latLng;
	boolean isFirstLoc = true;
	boolean isRequest = false;
	LocationClient locationClient;
	private View popView;
	private ActionUtil actionUtil;
	private TextView shopNameView;
	private TextView shopAdressView;
	private TextView shopPhoneView;
	private ImageView phoneimageView;
	private final int GET_STORE_LIST_SUCCESS = 2;
	private StoreInfo storeInfo;
	private List<StoreInfo> storeList;
	private Handler handle = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {

			case GET_STORE_LIST_SUCCESS:
				StoreModel storeModel = (StoreModel) msg.obj;
				storeList = storeModel.getShopList();
				for (int i = 0; i < storeList.size(); i++) {
					double longitude = storeList.get(i).getPoint().getY();
					double latitude = storeList.get(i).getPoint().getX();
					double[] gcj02_To_Bd09 = LocationUtils.gcj02_To_Bd09(latitude, longitude);
					LatLng point = new LatLng(gcj02_To_Bd09[0], gcj02_To_Bd09[1]);
					BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_marker);
					OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
					if (mBaiduMap!=null) {
						mBaiduMap.addOverlay(option);
					}
				}
				break;

			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.activity_near_gold_shop);
		initView();
		getStoreList();
	}

	private void getStoreList() {
		actionUtil = new ActionUtil(NearGoldShopActivity.this);
		actionUtil.getStoreList(0, 0, 0, "", 2);
		actionUtil.setOnPassBackListener(new OnPassBackListener() {

			@Override
			public void passBack(BaseModel model) {
				if (isFinishing()){
					return;
				}
				StoreModel storeModel = (StoreModel) model;
				if (storeModel == null) {
					UIHelper.showToast(NearGoldShopActivity.this, getString(R.string.rank_fail));
					return;
				}
				if (storeModel.getErrorMsg() != null) {
					UIHelper.showToast(NearGoldShopActivity.this, storeModel.getErrorMsg());

				} else {
					Message msg = new Message();
					msg.what = GET_STORE_LIST_SUCCESS;
					msg.obj = storeModel;
					handle.sendMessage(msg);
				}
			}
		});
	}

	private void initView() {
		mTitleView = (TitleView) findViewById(R.id.title_view);
		mTitleView.getTitletextView().setVisibility(View.VISIBLE);
		mTitleView.getTitletextView().setText("附近金店");
		mTitleView.getBackView().setVisibility(View.VISIBLE);
		mTitleView.getBackView().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		mMapView = (MapView) findViewById(R.id.bmapView);
		mMapView.showZoomControls(false);
		mMapView.removeViewAt(3);
		mBaiduMap = mMapView.getMap();
		mBaiduMap.setMyLocationEnabled(true);
		mBaiduMap.setOnMapClickListener(this);
		mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(LocationMode.NORMAL, true, null));
		getCurrentLocation();
		popView = super.getLayoutInflater().inflate(R.layout.nearshop_popview, null);
		mMapView.addView(this.popView, new MapView.LayoutParams(-2, -2));
		popView.setVisibility(View.GONE);
		popView.setOnClickListener(null);
		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {

			@Override
			public boolean onMarkerClick(Marker arg0) {
				popView.setVisibility(View.VISIBLE);
				shopNameView = (TextView) popView.findViewById(R.id.nearshop_name);
				shopAdressView = (TextView) popView.findViewById(R.id.nearshop_address);
				shopPhoneView = (TextView) popView.findViewById(R.id.nearshop_phone);
				phoneimageView = (ImageView) popView.findViewById(R.id.phone_button);

				LatLng ll = arg0.getPosition();
				Point p = mBaiduMap.getProjection().toScreenLocation(ll);
				p.y -= 90;
				LatLng llInfo = mBaiduMap.getProjection().fromScreenLocation(p);

				for (int i = 0; i < storeList.size(); i++) {

					double longitude = storeList.get(i).getPoint().getY();
					double latitude = storeList.get(i).getPoint().getX();
					double[] bd09_To_Gcj02 = LocationUtils.gcj02_To_Bd09(latitude, longitude);
					LatLng point = new LatLng(bd09_To_Gcj02[0], bd09_To_Gcj02[1]);
					if (ll.toString().equals(point.toString())) {
						storeInfo = storeList.get(i);
						shopNameView.setText(storeInfo.getShopName());
						shopAdressView.setText(storeInfo.getAddress());
						shopPhoneView.setText(storeInfo.getShopPhone());
						if ("".equals(storeInfo.getShopPhone())) {
							phoneimageView.setVisibility(View.GONE);
						} else {
							phoneimageView.setVisibility(View.VISIBLE);
						}
					}
				}
				InfoWindow infoWindow = new InfoWindow(popView, llInfo, -2);
				mBaiduMap.showInfoWindow(infoWindow);
				phoneimageView.setOnClickListener(new View.OnClickListener() {
					public void onClick(View paramAnonymousView) {

						UIHelper.showCallRemindDialog(NearGoldShopActivity.this, storeInfo.getShopPhone());
					}
				});
				return true;
			}
		});

	}

	private void getCurrentLocation() {
		locationClient = new LocationClient(getApplicationContext());
		LocationClientOption opClientOption = new LocationClientOption();
		opClientOption.setCoorType("bd09ll");
		opClientOption.setOpenGps(true);
		// opClientOption.setScanSpan(1000);
		opClientOption.setTimeOut(4000);
		locationClient.setLocOption(opClientOption);
		locationClient.registerLocationListener(new BDLocationListener() {
			@Override
			public void onReceiveLocation(BDLocation location) {
				latLng = new LatLng(location.getLatitude(), location.getLongitude());
				MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius()).direction(0)
						.latitude(location.getLatitude()).longitude(location.getLongitude()).build();
				mBaiduMap.setMyLocationData(locData);

				if (isRequest || isFirstLoc) {

					mBaiduMap.setMapStatus(MapStatusUpdateFactory
							.newMapStatus(new MapStatus.Builder().target(latLng).zoom(16).build()));
					isRequest = false;

				}
				isFirstLoc = false;

			}
		});
		locationClient.start();
		if (locationClient.isStarted() && locationClient != null) {
			locationClient.requestLocation();
		}
	}

	@Override
	protected void onDestroy() {

		locationClient.stop();
		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
		mBaiduMap=null;
		super.onDestroy();
	}

	@Override
	protected void onResume() {

		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onPause() {

		mMapView.onPause();
		super.onPause();
	}

	public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) {
		if (paramInt == KeyEvent.KEYCODE_BACK) {
			if ((this.popView != null) && (this.popView.getVisibility() == View.VISIBLE)) {
				popView.setVisibility(View.GONE);
				mBaiduMap.hideInfoWindow();
				return true;
			}
			finish();
			return false;
		}
		return super.onKeyDown(paramInt, paramKeyEvent);
	}

	@Override
	public void onMapClick(LatLng arg0) {
		if ((popView != null) && (popView.getVisibility() == View.VISIBLE)) {
			popView.setVisibility(View.GONE);
			mBaiduMap.hideInfoWindow();
		}
	}

	@Override
	public boolean onMapPoiClick(MapPoi arg0) {
		return false;
	}

}
